//
//  QianliMemberVC.swift
//  todoios
//
//  Created by qianli on 2025/4/17.
//

import Foundation
import UIKit
import SwiftyUserDefaults
import SVGKit
import PassKit
import StoreKit

class QianliMemberVC: QianliParentNaviVC {
    private var yYfZnCKFmQRnxYeI:UIImageView = UIImageView()
    private var jXpbrxMcMxCQdsDc:UILabel?
    private var ai6G1Cet7mWYFD4V:UILabel?
    private var ZYRF5ZPyDdU9kORK:UILabel?
    private var ARS0bJbeW0vnEMLd:UIButton?
    private var LtN3Dt85TpVGdejL:[VipMemberItem] = []
    private var kg5KBen4FwQgYwS6:[VipMemberItem] = []
    private var UOI88cgtfvLiZOxv:Int = 0
    private var yDCfMxMjoZSqnqxo:RetryNet?
    private var YSgwxXklgw9hk52r:MBProgressHUD?
    private var jIeweturIlJB6iP1:UIScrollView?
    private var OqkFl3NnS2mnklnS:Int = 0
    private var DzKXzGjYZ3Z78P0n:UIView?
    private var u6GDB3XSEFJ3CxcX:Int = 0
    private var WusamDXg09PmaJns:Bool = false
    private var RmDfowa8fqNCMjFK:Int = 0
    
    private var TSNV8TJjZSPRpwR7:UIButton?
    private var q7pFNMXPpoTTdhMY:[[String:Any]] = []
    
    private var RWPCLZ3xa9c7ZDrn:Timer?
    private var QFOBicWshStCh8so = PKPaymentAuthorizationStatus.failure
    
    // 内购商品列表
    private var _innerProducts = [SKProduct]()
    
    private var CFEQkGrnD0H33U2g:Bool = true
    private var K2bCupCAyWrz2PNE:UILabel = UILabel()
    private var noVH032UaoMcpN6U:UILabel = UILabel()
    private var EMUOnQRoTxMbImRK:UILabel = UILabel()
    private var qZgjj4OZzRk6rAE0:UILabel = UILabel()
    private var FoChj4XuuSpCuVaW:UILabel = UILabel()
    
//    public var invalid40101Block:((_ errMsg:String) -> Void)?
    
    deinit {
        SKPaymentQueue.default().remove(self) // ❗️ 缺少这行代码
        print("------QianliMemberVC.deinit")
    }
    
//    override func viewDidLoad() {
//        super.viewDidLoad()
//        self.GHL4Rhb91XYBer27()
//    }
    
//    override func viewDidAppear(_ animated: Bool) {
//        super.viewDidAppear(animated)
//        
//    }
    
    override func aB7kFqI8MB6DRPQC() {
        self.UiAkzwWfmh1dRxLN()
        self.UB01vocpkYNggNH2(0.5)
    }
    
    override func GHL4Rhb91XYBer27(){
        let imgW = qianli_pm_width
        let imgH = qianli_pm_width/509 * 309
        self.view.backgroundColor = UIColor.init(51, 102, 255)
        let topback = UIImageView(frame: CGRect(x: 0, y: 0, width: imgW, height: imgH)) //qianli_top_bg=509*309
        self.view.addSubview(topback)
        topback.image = "qianli_top_bg".qianli_R_image
        
        self.zdMpsGrNncVEHdYA(title: LocalizedString("Membership Center"),textColor: .white)
        
        //右上解加个刷新按钮，当用户信息出错时才显示，点击可以重新加载用户信息
        self.ARS0bJbeW0vnEMLd = UIButton(frame: CGRect(x: qianli_pm_width-25-24, y: self.topSpace-46/2-24/2, width: 24, height: 24))
        if let freshBtn = self.ARS0bJbeW0vnEMLd{
            self.view.addSubview(freshBtn)
//            freshBtn.setImage("qianli_refresh_user".qianli_R_image, for: .normal)
            freshBtn.qianli_button_image(image: "qianli_refresh_user".qianli_R_image,imgSize: CGSize(width: 24, height: 24),imgColor: .white)
//            freshBtn.isHidden = true //一直显示，方便不对的时候刷新显示
            freshBtn.touch_With_Block { [weak self] sender in
                if let self = self{
                    QianliVibrateEnum.selection.vibrate()
                    self.yYfZnCKFmQRnxYeI.qianli_image(imgurl: "qianliLoading.gif")
                    self.WsuwzksDZ3JcDz6m(1.0)
                }
            }
        }
        
        
        let userRowHeight = 100.0
        let titleBar = UIView(frame: CGRect(x: 15, y: topSpace+15, width: qianli_pm_width-30, height: userRowHeight))
        self.view.addSubview(titleBar)
//        titleBar.backgroundColor = .systemBackground
        titleBar.layer.cornerRadius = 10
        titleBar.tap_With_Block {[weak self] in
            if Defaults[\.isGuset]{
                self?.oFj2xilmy7vogXsc("")
            }
        }
        
        let avatarWidth = 70.0
        let itop = userRowHeight/2 - avatarWidth/2
        self.yYfZnCKFmQRnxYeI.frame = CGRect(x: 15, y: itop, width: avatarWidth, height: avatarWidth)
        titleBar.addSubview(self.yYfZnCKFmQRnxYeI)
        self.yYfZnCKFmQRnxYeI.layer.cornerRadius = avatarWidth / 2
        self.yYfZnCKFmQRnxYeI.clipsToBounds = true
        self.yYfZnCKFmQRnxYeI.qianli_image(imgurl: "qianliLoading.gif")
        
        
        let contentWidth = titleBar.bounds.width
        let iLeft = 15+avatarWidth+10
        let iRow = avatarWidth / 3.0
        let iLabelW = contentWidth-iLeft-10
        self.jXpbrxMcMxCQdsDc = UILabel(frame: CGRect(x: iLeft, y: itop, width: iLabelW, height: iRow))
        if let labeluser = self.jXpbrxMcMxCQdsDc{
            titleBar.addSubview(labeluser)
            labeluser.textColor = .white // .label
            labeluser.font = .systemFont(ofSize: 16)
            labeluser.text = "--"
        }

        self.ai6G1Cet7mWYFD4V = UILabel(frame: CGRect(x: iLeft, y: itop+iRow, width: iLabelW, height: iRow))
        if let labelvip = self.ai6G1Cet7mWYFD4V{
            titleBar.addSubview(labelvip)
            labelvip.textColor = .white // .secondaryLabel
            labelvip.font = .systemFont(ofSize: 15)
            labelvip.text = "\(LocalizedString("MEMBER LEVEL"))：----" //会员等级
        }
        
        self.ZYRF5ZPyDdU9kORK = UILabel(frame: CGRect(x: iLeft, y: itop+2*iRow, width: iLabelW, height: iRow))
        if let labelTime = self.ZYRF5ZPyDdU9kORK{
            titleBar.addSubview(labelTime)
            labelTime.textColor = .white //.secondaryLabel
            labelTime.font = .systemFont(ofSize: 15)
            labelTime.text = "\(LocalizedString("EXPIRE TIME"))：xxxx-xx-xx xx:xx:xx" //到期时间
        }
        
        let nextTop = topSpace+15+userRowHeight+15

        
        let workWidth = qianli_pm_width //-30
        let workView = UIView(frame: CGRect(x: 0, y: nextTop, width:workWidth , height: qianli_pm_height - nextTop)) // - bottomRowHeight
        view.addSubview(workView)
        workView.backgroundColor = .systemBackground
        workView.layer.cornerRadius = 30
        
        let highTextColor = UIColor.init(51, 102, 255)
        let btnWidth = 120.0
        let btnHeight = 24.0
        var iTop = 30.0
        let superMemberBtn = UIButton(frame: CGRect(x: workWidth/2/2 - btnWidth/2, y: iTop, width: btnWidth, height: btnHeight))
        workView.addSubview(superMemberBtn)
        superMemberBtn.setTitle(LocalizedString("Premium"), for: .normal)
        superMemberBtn.setTitleColor(highTextColor, for: .normal) //UIColor(hexString: "#ff4949")
        superMemberBtn.titleLabel?.font = .boldSystemFont(ofSize: 16)
        
        
        let normalMemberBtn = UIButton(frame: CGRect(x: workWidth/2 + workWidth/2/2 - btnWidth/2, y: iTop, width: btnWidth, height: btnHeight))
        workView.addSubview(normalMemberBtn)
        normalMemberBtn.setTitle(LocalizedString("Standard"), for: .normal)//"普通会员"
        normalMemberBtn.setTitleColor(.secondaryLabel, for: .normal) //UIColor(hexString: "#3964ff")
//        normalMemberBtn.backgroundColor = .cyan
        normalMemberBtn.titleLabel?.font = .boldSystemFont(ofSize: 16)
        
        superMemberBtn.touch_With_Block { [weak self,weak normalMemberBtn] sender in
            let msg = LocalizedString("Can Use All High-speed Nodes")
//            self?.alert_qianli_attributed_message(msg: "\n\(msg)",title: LocalizedString("Premium"), font: .systemFont(ofSize: 15), okTitle: LocalizedString("SURE"),alCenter: true)
            sender.setTitleColor(highTextColor, for: .normal)
            normalMemberBtn?.setTitleColor(.secondaryLabel, for: .normal)
            self?.V8Y8KCjBkxMbHFu6(0)
        }
        
        normalMemberBtn.touch_With_Block { [weak self,weak superMemberBtn] sender in
            let msg = LocalizedString("Can Use Partial High-speed Nodes")
//            self?.alert_qianli_attributed_message(msg: "\n\(msg)",title: LocalizedString("Standard"), font: .systemFont(ofSize: 15), okTitle: LocalizedString("SURE"),alCenter: true)
            sender.setTitleColor(highTextColor, for: .normal)
            superMemberBtn?.setTitleColor(.secondaryLabel, for: .normal)
            self?.V8Y8KCjBkxMbHFu6(1)
        }
        
        
        if let image = "qianli_ic_question".qianli_R_image{
            let resizedImage = image.try_qianli_resize(to: CGSize(width: 16, height: 16))?.withRenderingMode(.alwaysTemplate)
            var config = UIButton.Configuration.plain()
            config.image = resizedImage
            config.imagePlacement = .trailing // 将图标放置在文本右侧
            config.imagePadding = 5 // 设置图标和文本之间的间距
            config.baseForegroundColor = UIColor(hexString: "#ff4949")
//            superMemberBtn.configuration = config
            
            var n_config = UIButton.Configuration.plain()
            n_config.image = resizedImage
            n_config.imagePlacement = .trailing // 将图标放置在文本右侧
            n_config.imagePadding = 5 // 设置图标和文本之间的间距
            n_config.baseForegroundColor = UIColor(hexString: "#3964ff") //通过withRenderingMode及tintColor，可以改变图标的填充色
//            normalMemberBtn.configuration = n_config
        }
        
        var scrollTop = superMemberBtn.frame.maxY + 5.0
        
        let labelWidth = workWidth/2
        let superLabel = UIButton(frame: CGRect(x: 0, y: scrollTop, width: labelWidth, height: 24))
        workView.addSubview(superLabel)
        superLabel.setTitle(LocalizedString("100M/s Ultra-fast Line"), for: .normal)
        superLabel.setTitleColor(UIColor(hexString: "#ff4949"), for: .normal)
        superLabel.isHidden = true
        if let image = "qianli_member_svip".qianli_R_image {
            let resizedImage = image.try_qianli_resize(to: CGSize(width: 32, height: 16))//?.withRenderingMode(.alwaysTemplate), 不改变颜色不需要withRenderingMode
            var config_svip = UIButton.Configuration.plain()
            config_svip.image = resizedImage
            config_svip.imagePlacement = .leading // 将图标放置在文本右侧
            config_svip.imagePadding = 5 // 设置图标和文本之间的间距
//            config_svip.baseForegroundColor = UIColor(hexString: "#ff4949") //改变图片背景
            config_svip.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
                var outgoing = incoming
                outgoing.font = .systemFont(ofSize: 13)
                return outgoing
            }
//            superLabel.configuration = config_svip
        }
        
        let normalLabel = UIButton(frame: CGRect(x: workWidth/2, y: scrollTop, width: labelWidth, height: 24))
        workView.addSubview(normalLabel)
        normalLabel.setTitle(LocalizedString("10M/s High-speed Line"), for: .normal)
        normalLabel.setTitleColor(UIColor(hexString: "#3964ff"), for: .normal)
        normalLabel.isHidden = true
        if let image = "qianli_member_vip".qianli_R_image {
            let resizedImage = image.try_qianli_resize(to: CGSize(width: 32, height: 16))//?.withRenderingMode(.alwaysTemplate)
            var config = UIButton.Configuration.plain()
            config.image = resizedImage
            config.imagePlacement = .leading // 将图标放置在文本右侧
            config.imagePadding = 5 // 设置图标和文本之间的间距
//            config.baseForegroundColor = UIColor(hexString: "#3964ff") //改变图片背景
            config.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
                var outgoing = incoming
                outgoing.font = .systemFont(ofSize: 13)
                return outgoing
            }
//            normalLabel.configuration = config
        }
        
//        scrollTop = superLabel.frame.maxY + 15.0
        
        scrollTop = scrollTop + 15.0
        
        let line_1 = CALayer()
        workView.layer.addSublayer(line_1)
        line_1.frame = CGRect(x: 20, y: scrollTop, width: qianli_pm_width-40, height: 0.5)
        line_1.backgroundColor = UIColor.systemGray.cgColor
        
        scrollTop = scrollTop + 30.0
        
        self.jIeweturIlJB6iP1 = UIScrollView(frame: CGRect(x: 0, y: scrollTop, width: workWidth, height: workView.bounds.height - scrollTop))
        if let scrollview = self.jIeweturIlJB6iP1{
            workView.addSubview(scrollview)
            scrollview.isPagingEnabled = false
            scrollview.showsVerticalScrollIndicator = false
            scrollview.clipsToBounds = true
        }
        
        let iLeftSpace = 40.0
        let iMidSpace = 30.0 //中间20，两则30
        let selectBtnWidth = (workWidth - iLeftSpace*2 - iMidSpace)/2
        let selectBtnHeight = userRowHeight
        
       
        self.LtN3Dt85TpVGdejL.removeAll()
        for i in 0..<2{//高级
            let iTop = Double(i) * (selectBtnHeight + iMidSpace)
            let selectView1 = VipMemberItem.init(frame: CGRect(x: iLeftSpace, y: iTop, width: selectBtnWidth, height: selectBtnHeight),isSuper: true)
            if let scview = self.jIeweturIlJB6iP1{
                scview.addSubview(selectView1)
            }
            selectView1.tag = 100+i
            self.LtN3Dt85TpVGdejL.append(selectView1)
            selectView1.tap_With_Block {[weak selectView1,weak self] in
                QianliVibrateEnum.selection.vibrate()
                if let self = self, let selectview = selectView1{
                    print("supperMemberView.click:\(String(describing: selectview.tag))")
                    self.fRFdWaoG5KcYJxbC(itag: selectview.tag)
                }
            }
            
            let selectView2 = VipMemberItem.init(frame: CGRect(x: workWidth-iLeftSpace-selectBtnWidth, y: iTop, width: selectBtnWidth, height: selectBtnHeight),isSuper: true)
            if let scview = self.jIeweturIlJB6iP1{
                scview.addSubview(selectView2)
            }
            selectView2.tag = 100+i
            self.LtN3Dt85TpVGdejL.append(selectView2)
            selectView2.tap_With_Block {[weak selectView2,weak self] in
                QianliVibrateEnum.selection.vibrate()
                
                if let self = self,let selectview = selectView2{
                    print("supperMemberView.click:\(String(describing: selectview.tag))")
                    self.fRFdWaoG5KcYJxbC(itag: selectview.tag)
                }
            }
        }
        
        self.kg5KBen4FwQgYwS6.removeAll()
        for i in 0..<2{//普通
            let iTop =  Double(i) * (selectBtnHeight + iMidSpace)
            let selectView1 = VipMemberItem.init(frame: CGRect(x: iLeftSpace, y: iTop, width: selectBtnWidth, height: selectBtnHeight),isSuper: true)
            if let scview = self.jIeweturIlJB6iP1{
                scview.addSubview(selectView1)
            }
            selectView1.tag = 100+i
            self.kg5KBen4FwQgYwS6.append(selectView1)
            selectView1.tap_With_Block {[weak selectView1,weak self] in
                QianliVibrateEnum.selection.vibrate()
                if let self = self{
                    if (self.OqkFl3NnS2mnklnS>1){
                        self.view.Qianli_Toast(LocalizedString("Premium member and cannot downgrade to Standard!")) //您当前是高级会员，不能购买普通会员套餐！
                    }
                    else if let selectview = selectView1{
                        print("normalMemberView.click:\(String(describing: selectview.tag))")
                        self.fRFdWaoG5KcYJxbC(itag: selectview.tag)
                    }
                }
            }
            selectView1.isHidden = true
            
            let selectView2 = VipMemberItem.init(frame: CGRect(x: workWidth-iLeftSpace-selectBtnWidth, y: iTop, width: selectBtnWidth, height: selectBtnHeight),isSuper: false)
            if let scview = self.jIeweturIlJB6iP1{
                scview.addSubview(selectView2)
            }
            selectView2.tag = 200+i
            self.kg5KBen4FwQgYwS6.append(selectView2)
            selectView2.tap_With_Block {[weak self, weak selectView2] in
                QianliVibrateEnum.selection.vibrate()
                
                if let self = self{
                    if (self.OqkFl3NnS2mnklnS>1){
                        self.view.Qianli_Toast(LocalizedString("Premium member and cannot downgrade to Standard!")) //您当前是高级会员，不能购买普通会员套餐！
                    }
                    else if let selectview = selectView2{
                        print("normalMemberView.click:\(String(describing: selectview.tag))")
                        self.fRFdWaoG5KcYJxbC(itag: selectview.tag)
                    }
                }
            }
            selectView2.isHidden = true
        }
        
        let showCount = 2.0 //默认显示4行，根据需要可做调整，支持1-6行
        if let scview = self.jIeweturIlJB6iP1{
            scview.contentSize = CGSizeMake(workWidth, workView.bounds.height-100.0-scrollTop-20)
        }
        
        var lineTop = scrollTop + 2*selectBtnHeight + 2*iMidSpace
        let line_2 = CALayer()
        workView.layer.addSublayer(line_2)
        line_2.frame = CGRect(x: 20, y: lineTop, width: qianli_pm_width-40, height: 0.5)
        line_2.backgroundColor = UIColor.secondarySystemBackground.cgColor
        
        let vipTitle = UILabel(frame: CGRect(x: iLeftSpace, y: lineTop + 15.0, width: 100, height: 20))
        workView.addSubview(vipTitle)
        vipTitle.text = LocalizedString("Exclusive privilege")
        vipTitle.font = .boldSystemFont(ofSize: 16)
        let vipIco = UIImageView(frame: CGRect(x: iLeftSpace + 75 , y: lineTop + 15.0, width: 20, height: 20))
        workView.addSubview(vipIco)
        vipIco.image = "qianli_slider_item_a".qianli_R_image
        
        lineTop += 45
        let vipIco_1 = UIImageView(frame: CGRect(x: iLeftSpace, y: lineTop+40/2-12/2, width: 16, height: 12))
        workView.addSubview(vipIco_1)
        vipIco_1.image = "qianli_icons_tequan".qianli_R_image
        workView.addSubview(self.EMUOnQRoTxMbImRK)
        self.EMUOnQRoTxMbImRK.frame = CGRect(x: iLeftSpace+20, y: lineTop, width: 300, height: 40)
        self.EMUOnQRoTxMbImRK.text = LocalizedString("Ultra-Fast Exclusive: 100M/s")
        self.EMUOnQRoTxMbImRK.font = .systemFont(ofSize: 15)
        self.EMUOnQRoTxMbImRK.textColor = .label
        
        lineTop += 20+15
        let vipIco_2 = UIImageView(frame: CGRect(x: iLeftSpace, y: lineTop+40/2-12/2, width: 16, height: 12))
        workView.addSubview(vipIco_2)
        vipIco_2.image = "qianli_icons_tequan".qianli_R_image
        workView.addSubview(self.qZgjj4OZzRk6rAE0)
        self.qZgjj4OZzRk6rAE0.frame = CGRect(x: iLeftSpace+20, y: lineTop, width: 300, height: 40)
        self.qZgjj4OZzRk6rAE0.text = LocalizedString("All nodes unlocked, for professional-level needs")
        self.qZgjj4OZzRk6rAE0.font = .systemFont(ofSize: 15)
        self.qZgjj4OZzRk6rAE0.textColor = .label
        
        lineTop += 20+15
        let vipIco_3 = UIImageView(frame: CGRect(x: iLeftSpace, y: lineTop+40/2-12/2, width: 16, height: 12))
        workView.addSubview(vipIco_3)
        vipIco_3.image = "qianli_icons_tequan".qianli_R_image
        workView.addSubview(self.FoChj4XuuSpCuVaW)
        self.FoChj4XuuSpCuVaW.frame = CGRect(x: iLeftSpace+20, y: lineTop, width: 300, height: 40)
        self.FoChj4XuuSpCuVaW.text = LocalizedString("Supports 3 devices simultaneously")
        self.FoChj4XuuSpCuVaW.font = .systemFont(ofSize: 15)
        self.FoChj4XuuSpCuVaW.textColor = .label
        
        let bottomRowHeight = 100.0
        let bottomView = UIView(frame: CGRect(x: 0, y: qianli_pm_height-bottomRowHeight, width: qianli_pm_width, height: bottomRowHeight))
        self.view.addSubview(bottomView)
        bottomView.qianli_view_shadow(shadowColor: .secondarySystemBackground, offset: CGSize(width: 0, height: -5), opacity: 0.8, radius: 5)
        bottomView.backgroundColor = .systemBackground
        
        let rmbLabel = UILabel(frame: CGRect(x: 30, y: bottomRowHeight/2 - 30/2 + 3, width: 20, height: 30))
        bottomView.addSubview(rmbLabel)
        rmbLabel.text = "￥"
        rmbLabel.textColor = highTextColor
        rmbLabel.font = .boldSystemFont(ofSize: 15)
        bottomView.addSubview(self.K2bCupCAyWrz2PNE)
        self.K2bCupCAyWrz2PNE.frame = CGRect(x: rmbLabel.frame.maxX, y: bottomRowHeight/2 - 40/2 - 5, width: 100, height: 40)
        priceLabel.text = "0.0"
        priceLabel.textColor = highTextColor
        priceLabel.font = .boldSystemFont(ofSize: 36)
        bottomView.addSubview(self.noVH032UaoMcpN6U)
        self.noVH032UaoMcpN6U.frame = CGRect(x: 30, y: rmbLabel.frame.maxY-10, width: 75, height: 30)
        self.noVH032UaoMcpN6U.text = ""
        self.noVH032UaoMcpN6U.textColor = .label
        self.noVH032UaoMcpN6U.textAlignment = .center
        self.noVH032UaoMcpN6U.font = .systemFont(ofSize: 12)
        
        self.TSNV8TJjZSPRpwR7 = GradientBtn.init(frame: CGRect(x: qianli_pm_width - 20 - 130, y: bottomRowHeight/2 - 48/2 - 5, width: 130, height: 48), title: LocalizedString("Pay Now"))
//        UIButton(frame: CGRect(x: 15, y: 15, width: qianli_pm_width-3*15, height: 42))
        if let payBtn_Now = self.TSNV8TJjZSPRpwR7{
            bottomView.addSubview(payBtn_Now)
            payBtn_Now.touch_With_Block {[weak self] sender in
                self?.U6G2QSctGH6YCFmk(sender)
            }
        }
        
        oSyJBdhnR1VOGu65();
        
    }
    
    override func clFi25NuDNbscWXL() {
        self.RH3t0jO3qgqeWnNf()
        self.l0JOXR3PG9RznwqZ()
        self.h3wqTp4QEDNi67J0()
        super.clFi25NuDNbscWXL()
    }
    
    private func V8Y8KCjBkxMbHFu6(_ itabIndex:Int){
        if 0 == itabIndex{
            self.CFEQkGrnD0H33U2g = true
            self.EMUOnQRoTxMbImRK.text = LocalizedString("Ultra-Fast Exclusive: 100M/s")
            self.qZgjj4OZzRk6rAE0.text = LocalizedString("All nodes unlocked, for professional-level needs")
            self.FoChj4XuuSpCuVaW.text = LocalizedString("Supports 3 devices simultaneously")
        }else{
            self.CFEQkGrnD0H33U2g = false
            self.EMUOnQRoTxMbImRK.text = LocalizedString("High-Speed Exclusive: 10M/s")
            self.qZgjj4OZzRk6rAE0.text = LocalizedString("Nodes cover 80% of common needs")
            self.FoChj4XuuSpCuVaW.text = LocalizedString("Supports 2 devices simultaneously")
        }
        for item in self.kg5KBen4FwQgYwS6{
            item.isHidden = self.CFEQkGrnD0H33U2g
        }
        for item in self.LtN3Dt85TpVGdejL{
            item.isHidden = !self.CFEQkGrnD0H33U2g
        }
        
    }
    
    private func fRFdWaoG5KcYJxbC(itag:Int){
        if self.UOI88cgtfvLiZOxv>=100{
            //先恢复上一选择样式
            for item in self.kg5KBen4FwQgYwS6{
                item.eR3jFv8zTE3isREs(bkcolor: .systemBackground)
                item.layer.borderColor = UIColor.systemGray.cgColor
            }
            for item in self.LtN3Dt85TpVGdejL{
                item.eR3jFv8zTE3isREs(bkcolor: .systemBackground)
                item.layer.borderColor = UIColor.systemGray.cgColor
            }
        }
        
        if itag>=200{
            for item in self.kg5KBen4FwQgYwS6{
                if item.tag == itag{
                    self.UOI88cgtfvLiZOxv = itag
                    item.eR3jFv8zTE3isREs(bkcolor: UIColor(hexString: "#3964ff").withAlphaComponent(0.3))
                    item.layer.borderColor = UIColor(hexString: "#3964ff").cgColor
                    if !LoginViewModel.shared.darwin_reviewing{

                    }
                    let price = item.tSQvgMgiyIR3xjLy()
                    self.K2bCupCAyWrz2PNE.text = price
                    self.noVH032UaoMcpN6U.text = item.axiY63tGy3zH5FZz()
                    break
                }
            }
        }
        else if (itag>=100){
            for item in self.LtN3Dt85TpVGdejL{
                if item.tag == itag{
                    self.UOI88cgtfvLiZOxv = itag
                    item.eR3jFv8zTE3isREs(bkcolor: UIColor(hexString: "#3964ff").withAlphaComponent(0.3)) //ff4949
                    item.layer.borderColor = UIColor(hexString: "#3964ff").cgColor
                    if !LoginViewModel.shared.darwin_reviewing{
                        
                    }
                    let price = item.tSQvgMgiyIR3xjLy()
                    self.K2bCupCAyWrz2PNE.text = price
                    self.noVH032UaoMcpN6U.text = item.axiY63tGy3zH5FZz()
                    break
                }
            }
        }
    }
    
    private func h3wqTp4QEDNi67J0(){
        if let retryview =  self.yDCfMxMjoZSqnqxo{
            for childview in retryview.subviews{
                childview.removeFromSuperview()
            }
            retryview.removeFromSuperview()
        }
        self.yDCfMxMjoZSqnqxo = nil
    }
    
    private func dnOwhBpbw9jbgRH7(){
        let topSpace = UIDevice.qianli_statusbar_and_navibar_height()
        if(self.yDCfMxMjoZSqnqxo == nil){
            self.yDCfMxMjoZSqnqxo = RetryNet(frame: CGRect(x: 0, y: topSpace+5.0, width: qianli_pm_width, height: qianli_pm_height-topSpace-5.0))
            if let retryview = self.yDCfMxMjoZSqnqxo{
                self.view.addSubview(retryview)
                retryview.tapBlock = { [weak self] in
                    self?.fg6ThqypYwABic8E()
                }
            }
        }
    }
    
    private func OmDEptnSL46oDDwP(_ btn:UIButton, _ url:String){
        if !url.hasPrefix("http"){
            if let uiImage = url.qianli_R_image{
                let resizedImage = uiImage.try_qianli_resize(to: CGSize(width: 20, height: 20))
                var config = UIButton.Configuration.plain()
                config.image = resizedImage
                config.imagePadding = 15 // 设置图标和文本之间的间距
                btn.configuration = config
            }
            return
        }
        
        if let imageUrl = URL(string: url){
            let task = URLSession.shared.dataTask(with: imageUrl) { [weak btn] (data, response, error) in
                if let error = error {
                    QianliUniversalFunc.QianliLog("Error loading image: \(error)")
                    return
                }
                
                guard let data = data else {
                    QianliUniversalFunc.QianliLog("No data received")
                    return
                }
                
                DispatchQueue.global().async {
                    if let uiImage = UIImage(data: data) {
                        // 回到主线程更新 UI
                        DispatchQueue.main.async {
                            if let button = btn{
                                let resizedImage = uiImage.try_qianli_resize(to: CGSize(width: 20, height: 20))
                                var config = UIButton.Configuration.plain()
                                config.image = resizedImage
                                config.imagePadding = 15 // 设置图标和文本之间的间距
                                button.configuration = config
                            }
                        }
                    }
                }
            }
           // 启动任务
            task.resume()
        }
    }
    
    private func GXwrjdpULOsWeoiB(avatar:String){
        if Defaults[\.isGuset]{
            self.yYfZnCKFmQRnxYeI.image = "qianli_slider_guesthead".qianli_R_image
            return
        }
        if avatar.isEmpty{
            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
            return
        }
        if let imageUrl = URL(string: LoginViewModel.shared.url_JKou + avatar){
            if imageUrl.pathExtension.lowercased() == "svg" { //svg类型图标特殊处理
//              imgHeader.image =  SVGKImage(contentsOf: imageUrl).uiImage //同步加载SVG图片
                let task = URLSession.shared.dataTask(with: imageUrl) { [weak self] (data, response, error) in
                    if let self = self{
                        if let error = error {
                            QianliUniversalFunc.QianliLog("Error loading image: \(error)")
                            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                            return
                        }
                        
                        guard let data = data else {
                            QianliUniversalFunc.QianliLog("No data received")
                            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                            return
                        }
                        
                        // 在后台线程解析 SVG 数据
                        DispatchQueue.global().async {
                            if let svgImage = SVGKImage(data: data) {
                                let uiImage = svgImage.uiImage
                                // 回到主线程更新 UI
                                DispatchQueue.main.async {
                                    self.yYfZnCKFmQRnxYeI.image = uiImage
                                }
                            }else{
                                DispatchQueue.main.async {
                                    self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                                }
                            }
                        }
                    }
                    
                }
               // 启动任务
                task.resume()
            }else{
                self.yYfZnCKFmQRnxYeI.sd_setImage(with: imageUrl, placeholderImage: nil) { [weak self](image, error, cacheType, url) in
                    if error != nil || image == nil{
                        if let self = self{
                            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
                        }
                    }
                }
            }
        }else{
            self.yYfZnCKFmQRnxYeI.image = "qianli_placeholder".qianli_R_image
        }
    }
    
    private func HaBjqrPksgDI8DHj(on label:UILabel,with newTitle:String,and normalText:String,and fontsize:CGFloat){
//富文本
        let myMutableString = NSMutableAttributedString(
                    string: newTitle,
                    attributes: [NSAttributedString.Key.font:UIFont.systemFont(ofSize: fontsize),
                                 NSAttributedString.Key.foregroundColor:UIColor.white])//UIColor(hexString: "#3964ff")
        let range_N:NSRange = (newTitle as NSString).range(of:normalText)
        myMutableString.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.white], range: range_N) //secondaryLabel
        label.attributedText = myMutableString
    }
    
}

extension QianliMemberVC{
    private func U6G2QSctGH6YCFmk(_ sender:UIButton){
        if self.UOI88cgtfvLiZOxv<100{
            self.view.Qianli_Toast(LocalizedString("Select a product"))//请选择商品
            return
        }
        
        if self.UOI88cgtfvLiZOxv>=200{
            if LoginViewModel.shared.darwin_reviewing{
//                if let bid = QianliAppEnvStruct.appBid{
                    let sid = "\(self.UOI88cgtfvLiZOxv-200)"
                    //--------
                    mbeGa3nrmNMK8yja(sid)
//                }
            }else{
                BQrHNspvtcZqLlGI(itag: self.UOI88cgtfvLiZOxv-200)
            }
        }else if self.UOI88cgtfvLiZOxv>=100{
            if LoginViewModel.shared.darwin_reviewing{
//                if let bid = QianliAppEnvStruct.appBid{
                    let sid = "\(self.UOI88cgtfvLiZOxv-100)"
                    //--------
                    mbeGa3nrmNMK8yja(sid)
//                }
            }else{
                BQrHNspvtcZqLlGI(itag: self.UOI88cgtfvLiZOxv-100)
            }
        }
    }
    
    private func BXDRRVlTXA9DLOKc(_ errMsg:String){
        if !errMsg.isEmpty{
            self.l0JOXR3PG9RznwqZ()
            self.view.Qianli_Toast(errMsg)
            return
        }
        VipViewModel.shared.XiambxbVszW7LFim {[weak self] result in
            DispatchQueue.main.async {
                switch result{
                case .success(let orderinfo):
                    if orderinfo.code == 0{
                        self?.eCoXsX2klqBeiNmo("")
                    }else{
                        self?.eCoXsX2klqBeiNmo("[\(orderinfo.code)]\(orderinfo.msg)")
                    }
                case .failure(let err):
                    self?.eCoXsX2klqBeiNmo(err.localizedDescription)
                }
            }
        }
    }
    
    private func eCoXsX2klqBeiNmo(_ errMsg:String){
        self.l0JOXR3PG9RznwqZ()
    }
    
    private func DOzHfW7rlsvJQoeK(_ errMsg:String){
        if !errMsg.isEmpty{
            self.l0JOXR3PG9RznwqZ()
            self.view.Qianli_Toast(errMsg)
            return
        }
        
        VipViewModel.shared.QLq8RYY7nk51xXYT(completion: {[weak self] result in
            DispatchQueue.main.async {
                switch result{
                case .success(let orderinfo):
                    if orderinfo.code == 0{
                        self?.atOFsHijBYGFXxEt("")
                    }else{
                        self?.atOFsHijBYGFXxEt("[\(orderinfo.code)]\(orderinfo.msg)")
                    }
                case .failure(let err):
                    self?.atOFsHijBYGFXxEt(err.localizedDescription)
                }
            }
        })
    }
    
    private func atOFsHijBYGFXxEt(_ errMsg:String){
        if !errMsg.isEmpty{
            self.l0JOXR3PG9RznwqZ()
            self.view.Qianli_Toast(errMsg)
            return
        }
        self.RmDfowa8fqNCMjFK = 0
        nrkUipNAGkBYmYoW()
    }
    
    @objc func nrkUipNAGkBYmYoW(){
        self.RmDfowa8fqNCMjFK += 1
        VipViewModel.shared.k4Yncbet8g58oOuU(completion: {[weak self] result in
            DispatchQueue.main.async {
                switch result{
                case .success(let orderinfo):
                    if orderinfo.code == 0{
                        self?.KX0ctAsGS1Y7rRZT("")
                    }else{
                        self?.KX0ctAsGS1Y7rRZT("[\(orderinfo.code)]\(orderinfo.msg)")
                    }
                case .failure(let err):
                    self?.KX0ctAsGS1Y7rRZT(err.localizedDescription)
                }
            }
        })
    }
    
    private func KX0ctAsGS1Y7rRZT(_ errMsg:String){
        if (errMsg.isEmpty){

        }else{

        }
    }
    
    private func VYM10wkBobkogIvg(_ errMsg:String,_ url:String){
        self.l0JOXR3PG9RznwqZ()
        
        if errMsg.isEmpty {
            self.IBcJid76vYT4lxNL()
            if self.WusamDXg09PmaJns{
                zs6YxzqWph4jUZU8(url)
                self.VputtY0ActT7f5o0()
            }else{
                let encodeUrl = OwfN0pY84aBgeJjP(url)
                if let tmpdomain = "YWxpcGF5czovL3BsYXRmb3JtYXBpL3N0YXJ0YXBwP2FwcElkPTIwMDAwMDY3".qianli_safe_base64_decode(){
                    let sUrlScheme = "\(tmpdomain)&url=\(encodeUrl)"
                    QianliUniversalFunc.B6NlI6IEEQDFXLK3(sUrlScheme) {[weak self] success in
                        if !success{
                            DispatchQueue.main.async {
                                if let str = "5peg5rOV5omT5byA5pSv5LuY5a6d77yM6K+356Gu6K6k5bey5a6J6KOF5pSv5LuY5a6dQXBw5ZCO6YeN6K+VIQ==".qianli_safe_base64_decode(){
                                    self?.view.Qianli_Toast(str)
                                }else{
                                    self?.view.Qianli_Toast("Failed")
                                }
                            }
                        }else{
                            DispatchQueue.main.async {
                                self?.VputtY0ActT7f5o0()
                            }
                        }
                    }
                }
            }
        }else{
            self.view.Qianli_Toast(errMsg)
        }
    }
    
    private func BQrHNspvtcZqLlGI(itag:Int){
        let token = Defaults[\.token]
        let timestamp = Int64(Date().timeIntervalSince1970 * 1000)
        if let web = "d2VicGF5".qianli_safe_base64_decode(){
            let url = "\(LoginViewModel.shared.url_JKou)/\(web)/#/?token=\(token)&id=\(itag)&time=\(timestamp)"
            QianliUniversalFunc.B6NlI6IEEQDFXLK3(url) { success in
                
            }
        }
    }
    
    private func OwfN0pY84aBgeJjP(_ string: String) -> String {
        let allowedCharacters = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted
        return string.addingPercentEncoding(withAllowedCharacters: allowedCharacters) ?? string
    }
    
    private func zs6YxzqWph4jUZU8(_ url:String){
        IBcJid76vYT4lxNL()
        
        self.DzKXzGjYZ3Z78P0n = UIView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: qianli_pm_height))
        if let alertBgView = self.DzKXzGjYZ3Z78P0n{
            view.addSubview(alertBgView)
            alertBgView.backgroundColor = .black.withAlphaComponent(0.8)
            let content_w = 320.0
            let content_h = 320.0
            let contentView = UIView(frame: CGRect(x: qianli_pm_width/2-content_w/2, y: qianli_pm_height/2-content_h/2-80, width: content_w, height: content_h))
            alertBgView.addSubview(contentView)
            contentView.backgroundColor = .white
            contentView.layer.cornerRadius = 12
            
            let titleLabel = UILabel(frame: CGRect(x: 10, y: 0, width: content_w-20, height: 60))
            contentView.addSubview(titleLabel)
            titleLabel.text = "6K+35oiq5bGP5ZCO55So5pSv5LuY5a6d5omr56CB5pSv5LuY".qianli_safe_base64_decode()
            titleLabel.textColor = .black
            titleLabel.textAlignment = .center
            titleLabel.font = .systemFont(ofSize: 18)
            
            let imgView = UIImageView(frame: CGRect(x: 60, y: 60, width: 320-120, height: 320-120))
            contentView.addSubview(imgView)
            imgView.qianli_image(imgurl: "qianliLoading.gif")
            imgView.backgroundColor = .white
            
            DispatchQueue.global(qos: .userInitiated).async {//.userInitiated 既保证响应速度，又不会抢占 UI 线程资源
                if let qrCodeImage = QianliQRCode.generate_qianli_qrcode_withLogo(from: url, logo: "qianli_logo_main".qianli_R_image){
                    DispatchQueue.main.async {[weak imgView] in
                        imgView?.image = qrCodeImage
                    }
                }
            }
            
            
            let btn = UIButton(frame: CGRect(x: content_w/2 - 80/2, y: content_h-15-30, width: 80, height: 30))
            contentView.addSubview(btn)
            btn.setTitle(LocalizedString("SURE"), for: .normal)
            btn.setTitleColor(.systemBlue, for: .normal)
            btn.titleLabel?.font = .systemFont(ofSize: 16)
            btn.touch_With_Block {[weak self] sender in
                self?.IBcJid76vYT4lxNL()
            }
        }
    }
    
    private func X7mzGj0bAwUxh3gP(_ btnImg:UIImage?){
        IBcJid76vYT4lxNL()
        
        self.DzKXzGjYZ3Z78P0n = UIView(frame: CGRect(x: 0, y: 0, width: qianli_pm_width, height: qianli_pm_height))
        if let alertBgView = self.DzKXzGjYZ3Z78P0n{
            view.addSubview(alertBgView)
            alertBgView.backgroundColor = .black.withAlphaComponent(0.8)
            alertBgView.alpha = 0
            
            let content_w = 300.0
            let content_h = 380.0
            let contentView = UIView(frame: CGRect(x: qianli_pm_width/2-content_w/2, y: qianli_pm_height/2-content_h/2-100, width: content_w, height: content_h))
            alertBgView.addSubview(contentView)
            let contentbgView = UIView(frame: CGRect(x: 0, y: 70, width: content_w, height: content_h-70))
            contentView.addSubview(contentbgView)
            contentbgView.backgroundColor = .secondarySystemBackground
            contentbgView.layer.cornerRadius = 12
            
            let imgView = UIImageView(frame: CGRect(x: 0, y: 0, width: content_w, height: 150))
            contentView.addSubview(imgView)
            
            let label = UILabel(frame: CGRect(x: 15, y: 180, width: content_w-30, height: 20))
            contentView.addSubview(label)
            label.font = .systemFont(ofSize: 15)
            label.textColor = .label
            label.text = "6K+36YCJ5oup5pSv5LuY5pa55byP".qianli_safe_base64_decode()
            
            let btnApp = UIButton(frame: CGRect(x: 20, y: content_h-30-48, width: content_w-40, height: 48))
            contentView.addSubview(btnApp)
            let apzf = "5pSv5LuY5a6dQXBw5pSv5LuY".qianli_safe_base64_decode()
            btnApp.setTitle(apzf, for: .normal)
            btnApp.setTitleColor(.label, for: .normal)
            btnApp.titleLabel?.font = .systemFont(ofSize: 14)
            btnApp.layer.cornerRadius = 12
            btnApp.backgroundColor = .systemBackground
            btnApp.touch_With_Block {[weak self] sender in
                if let self = self{
                    self.WusamDXg09PmaJns=false
                }
            }
            
            let btnCode = UIButton(frame: CGRect(x: 20, y: content_h-30-48-25-48, width: content_w-40, height: 48))
            contentView.addSubview(btnCode)
            let smzf = "5pSv5LuY5a6d5omr56CB5pSv5LuY".qianli_safe_base64_decode()
            btnCode.setTitle(smzf, for: .normal)
            btnCode.setTitleColor(.label, for: .normal)
            btnCode.titleLabel?.font = .systemFont(ofSize: 14)
            btnCode.backgroundColor = .systemBackground
            btnCode.layer.cornerRadius = 12
            btnCode.touch_With_Block { [weak self]sender in
                if let self = self{
                    self.WusamDXg09PmaJns=true
                }
            }
            if let ali_img = btnImg{
                let resizedImage = ali_img.try_qianli_resize(to: CGSize(width: 20, height: 20))
                var config = UIButton.Configuration.plain()
                config.image = resizedImage
                config.imagePadding = 15 // 设置图标和文本之间的间距
                btnApp.configuration = config
                btnCode.configuration = config
            }
            
            let closeBtn = UIButton(frame: CGRect(x: alertBgView.bounds.width/2 - 30/2, y: contentView.frame.maxY+50, width: 30, height: 30))
            alertBgView.addSubview(closeBtn)
            closeBtn.setImage("qianli_alert_btclose".qianli_R_image, for: .normal)
            closeBtn.touch_With_Block {[weak self] sender in
                self?.HE2RiTt0ioEysZG6(false)
            }
        }
        HE2RiTt0ioEysZG6(true)
    }
    
    private func HE2RiTt0ioEysZG6(_ isShow:Bool){
        UIView.animate(withDuration: 0.25, delay: 0,options: [.curveEaseInOut]) {[weak self] in
            if let self=self,let alertBgView = self.DzKXzGjYZ3Z78P0n{
                alertBgView.alpha = isShow ? 1 : 0
            }
        } completion: { [weak self] _ in
            self?.h3wqTp4QEDNi67J0()
        }
         
    }
    private func IBcJid76vYT4lxNL(){
        if let alertBgView = self.DzKXzGjYZ3Z78P0n{
            for child in alertBgView.subviews{
                child.removeFromSuperview()
            }
            alertBgView.removeFromSuperview()
        }
        self.DzKXzGjYZ3Z78P0n = nil
    }

}

extension QianliMemberVC{
    private func kcjVZK2HalwMh2oW(_ status:String){
        if status == "TRADE_SUCCESS"{
            self.RH3t0jO3qgqeWnNf()
            self.IBcJid76vYT4lxNL()
            self.alert_qianli_message(LocalizedString("Payment Successful"), message: LocalizedString("Congratulations! Payment completed")){//订单支付成功//恭喜您支付成功！
                self.UiAkzwWfmh1dRxLN()
            }
            
        }else if status == "TRADE_CLOSED"{
            self.RH3t0jO3qgqeWnNf()
            self.IBcJid76vYT4lxNL()
            self.view.Qianli_Toast(LocalizedString("Order has been closed!"))//订单已关闭！
        }
    }
    
    private func VputtY0ActT7f5o0(){
        RH3t0jO3qgqeWnNf()
        
        self.RWPCLZ3xa9c7ZDrn = Timer(timeInterval: 2, repeats: true, block: {[weak self] _ in
            if let self = self{
                VipViewModel.shared.J85uYzv7U9QtRAtT { result in
                    switch result{
                    case .success(let data):
                        if data.code == 0{
                            if data.msg == "TRADE_SUCCESS" || data.msg == "TRADE_CLOSED"{
//                                "WAIT_BUYER_PAY"待支付 "TRADE_SUCCESS"表示完成,"TRADE_CLOSED"表示关闭
                                DispatchQueue.main.async {
                                    self.kcjVZK2HalwMh2oW(data.msg)
                                }
                            }else{
                                print("startOkSpy: \(data.msg)")
                            }
                        }
                    case .failure(let error):
                        print("getOrderData>err: \(error.localizedDescription)")
                    }
                }
            }
        })
        if let timer = self.RWPCLZ3xa9c7ZDrn{
            RunLoop.main.add(timer, forMode: .common)
            timer.fire()
        }
    }
    private func RH3t0jO3qgqeWnNf(){
        if let timer = self.RWPCLZ3xa9c7ZDrn{
            timer.invalidate()
        }
        self.RWPCLZ3xa9c7ZDrn = nil
    }
}

extension QianliMemberVC{
    private func flM9woQKzM3ymMZp(_ errMsg:String){
        //表示登录失效，退出登录，清空信息，显示登录UI
//        self.clFi25NuDNbscWXL()
//        self.invalid40101Block?(errMsg)
        self.oFj2xilmy7vogXsc(errMsg)
    }
    
    private func WsuwzksDZ3JcDz6m(_ time:TimeInterval){
        if let btn = self.ARS0bJbeW0vnEMLd{
            btn.isEnabled = false
        }
        self.perform(#selector(UiAkzwWfmh1dRxLN), with: nil, afterDelay: time)
    }
    
    @objc func UiAkzwWfmh1dRxLN(){
        self.yYfZnCKFmQRnxYeI.qianli_image(imgurl: "qianliLoading.gif")
      
        UserInfoViewModel.shared.MuIZuRZXjs2PfsXX { result in
            DispatchQueue.main.async {[weak self] in
                switch result{
                case .success(let baseData):
                    if baseData.code == 0{
                        self?.IW8gULUFSJCWG7Js("")
                    }else if baseData.code == 40101{
                        self?.flM9woQKzM3ymMZp(baseData.msg)
                    } else{
                        self?.IW8gULUFSJCWG7Js("[\(baseData.code)]\(baseData.msg)")
                    }
                case .failure(let err):
                    self?.IW8gULUFSJCWG7Js(err.localizedDescription)
                }
            }
        }
    }
    
    private func IW8gULUFSJCWG7Js(_ errMsg:String){
        self.ARS0bJbeW0vnEMLd?.isEnabled = true
        if errMsg.isEmpty{
            if let labeluser =  self.jXpbrxMcMxCQdsDc{
                labeluser.text = Defaults[\.username]
            }
            self.OqkFl3NnS2mnklnS = Defaults[\.memberLevel]
            if let labelvip = self.ai6G1Cet7mWYFD4V{
                let levelStr = "\(LocalizedString("MEMBER LEVEL"))：" + QianliUtils.shared.getLevel(level:self.OqkFl3NnS2mnklnS)
                HaBjqrPksgDI8DHj(on: labelvip, with: levelStr, and: "\(LocalizedString("MEMBER LEVEL"))：", and: 15.0)
                if self.OqkFl3NnS2mnklnS > 1{
                    for item in self.kg5KBen4FwQgYwS6{
                        item.DYybO9LYqGsn71sn() //所有普通会员置灰,//本身是高级会员，则不能点击普通会员
                    }
                }
            }
            if let labeTime = self.ZYRF5ZPyDdU9kORK{
                if !Defaults[\.memberexpiryat].isEmpty{
                   let iso8601String = Defaults[\.memberexpiryat]
                   let formatTime = "\(LocalizedString("EXPIRE TIME"))：" + isoDate2Formatdate(iso8601String)
                    HaBjqrPksgDI8DHj(on: labeTime, with: formatTime, and: "\(LocalizedString("EXPIRE TIME"))：", and: 15.0)
                }
            }
            GXwrjdpULOsWeoiB(avatar: Defaults[\.avatar])
        }else{
            view.Qianli_Toast(errMsg)
        }
    }
    
    private func UB01vocpkYNggNH2(_ time:TimeInterval){
        self.M62h1bVOydwY8i4y(LocalizedString("Loading, please wait..."))//"正在加载,请稍候..."
        self.perform(#selector(fg6ThqypYwABic8E), with: nil, afterDelay: time)
        
    }
    
    @objc func fg6ThqypYwABic8E(){
        VipViewModel.shared.ZCYappMADpwrfWpt(goodsRequest: GoodsRequest(goods_type: GoodsType.member.rawValue)) { result in
            DispatchQueue.main.async {[weak self] in
                switch result{
                case .success(let data):
                    if data.code == 0{
                        self?.mxTRuEPEWorJ7YQz("")
                    }else if data.code == 40101{
                        self?.flM9woQKzM3ymMZp(data.msg)
                    } else{
                        self?.mxTRuEPEWorJ7YQz(data.msg)
                    }
                case .failure(let err):
                    self?.mxTRuEPEWorJ7YQz(err.localizedDescription)
                }
                
            }
        }
    }
    
    private func mxTRuEPEWorJ7YQz(_ errMsg:String){
        self.l0JOXR3PG9RznwqZ()
        if (errMsg.isEmpty && VipViewModel.shared.goodsList.count>0){
//解析数据，然后显示到各selectBtn上
            let senorList = VipViewModel.shared.goodsList.filter( {$0.member_level == 2})
            if self.LtN3Dt85TpVGdejL.count>0{
                for (index,item) in senorList.enumerated(){
                    if (!item.des.isEmpty && index<self.LtN3Dt85TpVGdejL.count){
                        if let cardInfo = self.zZWSwzxWTgh7p2N0(item.des){
                            let goodid = item.id
                            self.LtN3Dt85TpVGdejL[index].ElKjT0XoruF4uLja(title: cardInfo.name, price: cardInfo.price, averagePrice: cardInfo.averagePrice)
                            self.LtN3Dt85TpVGdejL[index].tag = 100+goodid
                            self.LtN3Dt85TpVGdejL[index].isHidden = !self.CFEQkGrnD0H33U2g
                        }
                    }
                }
            }
            
            let normalList = VipViewModel.shared.goodsList.filter( {$0.member_level == 1})
            if self.kg5KBen4FwQgYwS6.count>0{
                for (index,item) in normalList.enumerated(){
                    if (!item.des.isEmpty && index<self.kg5KBen4FwQgYwS6.count){
                        if let cardInfo = self.zZWSwzxWTgh7p2N0(item.des){
                            let goodid = item.id
                            self.kg5KBen4FwQgYwS6[index].ElKjT0XoruF4uLja(title: cardInfo.name, price:cardInfo.price, averagePrice: cardInfo.averagePrice)
                            self.kg5KBen4FwQgYwS6[index].tag = 200+goodid
                            self.kg5KBen4FwQgYwS6[index].isHidden = self.CFEQkGrnD0H33U2g
                        }
                    }
                }
            }
            
            let imax = min(max(senorList.count, normalList.count),6)
            let workWidth = qianli_pm_width-30
            let selectBtnHeight = 100.0
            if let scview = self.jIeweturIlJB6iP1{
                scview.contentSize = CGSizeMake(workWidth, CGFloat(imax)*selectBtnHeight + CGFloat(imax)*15.0)
            }
            
            self.h3wqTp4QEDNi67J0()

            self.eCoXsX2klqBeiNmo("")

           
        }else{
//        显示重试UI，
            dnOwhBpbw9jbgRH7()
            if let review = self.yDCfMxMjoZSqnqxo{
                review.vSXenwySp9gyesbp(LocalizedString("Load Failed. Please check network & try again!"))//"数据请求失败，请确认网络连接后重试!"
                review.isHidden = false
            }
            
            self.kjUCAXJJZtBBnblZ(errMsg)
        }
    }
    
    private func zZWSwzxWTgh7p2N0(_ jsonString: String) -> CardInfo? {
        guard let jsonData = jsonString.data(using:.utf8) else {
            return nil
        }
        do {
            let decoder = JSONDecoder()
            let cardInfo = try decoder.decode(CardInfo.self, from: jsonData)
            return cardInfo
        }catch {
            print("JSON 解码出错：\(error)")
        }
        return nil
    }
}

extension QianliMemberVC{
    private func OBdGqK2NayND5sVq(_ msg:String){
        DispatchQueue.main.async {[weak self] in
            if let self = self{
                self.l0JOXR3PG9RznwqZ()
                 
                self.YSgwxXklgw9hk52r = MBProgressHUD.showAdded(to: self.view, animated: true)
                if let loadinghud = self.YSgwxXklgw9hk52r,!msg.isEmpty{
                    loadinghud.label.text = msg
                }
            }
        }
    }
    
    private func TdH6cK5YxjD3HtG2(){
        if let loadinghud = self.YSgwxXklgw9hk52r{
            loadinghud.hide(animated: true)
        }
        self.YSgwxXklgw9hk52r = nil
    }
    
    private func oFj2xilmy7vogXsc(_ errmsg:String){
        let loginvc = QainliUserLoginVC()
        loginvc.modalPresentationStyle = .overFullScreen
        if !errmsg.isEmpty{
            loginvc.drLNPcLilSQNLR0o(errmsg)
        }
        self.present(loginvc, animated: true)
        loginvc.loginOKBlock = {
            DispatchQueue.main.async {[weak self] in
                if let self = self{
                    self.view.Qianli_Toast(LocalizedString("Login Success!")) //"登录成功！"
                    //更新用户信息 //更新商品信息
                    self.UiAkzwWfmh1dRxLN()
                }
            }
        }
    }
}


extension QianliMemberVC:SKProductsRequestDelegate,SKPaymentTransactionObserver{
    
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        _innerProducts = response.products
        // 打印未找到的产品ID（用于调试）
        for invalidID in response.invalidProductIdentifiers {
            print("无效的产品ID: \(invalidID)")
        }
        print("productsRequest>innerProducts:",_innerProducts.count)
//        if innerProducts.count == 1{ //每次内购都刷新商品
//            vVjJop3T5uPVpN2z(innerProducts[0].productIdentifier)
//        }
    }
    
    // 请求商品列表
    func oSyJBdhnR1VOGu65(_ productId:String = "") {
        guard SKPaymentQueue.canMakePayments() else {
            self.view.Qianli_Toast(LocalizedString("Device Not Support"))//"设备不允许内购"
            return
        }
        let productIDs: Set<String>
        if(productId.isEmpty){
            productIDs = ["08", "09", "10", "11", "12", "13", "14", "15"]
            SKPaymentQueue.default().add(self)
        }else{
            productIDs = [productId]
        }
//        let productIDs = (productId.isEmpty) ? Set(["08", "09", "10", "11", "12", "13", "14", "15"]) : Set([productId])
        let request = SKProductsRequest(productIdentifiers: productIDs)
        request.delegate = self
        request.start()
    }
    
    func mbeGa3nrmNMK8yja(_ productIdentifier: String) {
        DispatchQueue.main.async {[weak self] in
            if let self=self, let sender = self.TSNV8TJjZSPRpwR7{
                sender.setTitle(LocalizedString("Subscribing..."), for: .normal)
                sender.isEnabled = false
            }
        }
        
        let sid = (productIdentifier.count == 1) ? "0\(productIdentifier)" : productIdentifier
//每次内购都刷新该商品模式：
//        oSyJBdhnR1VOGu65(sid)
//不用刷新模式：
        vVjJop3T5uPVpN2z(sid)
    }
    
    func vVjJop3T5uPVpN2z(_ productIdentifier: String) {
        guard let product = _innerProducts.first(where: { $0.productIdentifier == productIdentifier }) else {
            let notexist = LocalizedString("Subscription Not Exist")
//            self.view.Qianli_Toast("\(notexist): \(productIdentifier)")
            self.Ep3SoScAZ7qRlxNy("\(notexist): \(productIdentifier)")
            //同时刷新该商品：
            oSyJBdhnR1VOGu65(productIdentifier)
            return
        }
        
        // 获取货币代码（如 "CNY", "USD"）
       let currencyCode = product.priceLocale.currencyCode ?? "unkown"
       // 获取国家代码（从 Locale 推断）
       let countryCode = product.priceLocale.regionCode ?? "unkown"
        
        print("purchaseProductWithIdentifier>currencyCode=\(currencyCode),countryCode=\(countryCode)")
        //currencyCode=CNY,countryCode=CN ,大陆测试账号
        //currencyCode=JPY,countryCode=JP ,日本测试账号
        // 沙盒下测试，会有缓存问题，大陆账号退出，再次购买，此处获取仍是CN，反之也一样，日本账号登录退出后，显示的仍是JP
        //SKPaymentQueue.default().add(payment) 之后才会弹出登录框，而即使登录了另一个地区的账号后，显示的仍是上一次账号的地区，
        //此时要退出，再进来，执行一下requestProducts，相当于刷新一下商品，此处才会返回新账号的地区，所以改为每次购买都刷新商品

        if (countryCode.uppercased() == "CN") { // && WEYB1XUAo2P2ZCtt()
//这种判断，如果是在账号退出的情况下，本来是可以弹出登录账号对话框的，结果因为上一账号的地区信息，导致被误判断，从而直接拦截掉了
//要用户自行去AppStore登录后，此时再来订阅，才OK。
            self.alert_qianli_message(LocalizedString("Can not Purchase"), message: LocalizedString("Current Apple ID country/region does not support. Please change your Apple ID region or use a different account."),okTitle: LocalizedString("LINK US")) {
                let customUrl = Defaults[\.customerURL]
                QianliUniversalFunc.PqHXCLMrbGaK2xN1(customUrl) { success in
                }
            }
            return
        }
     
        self.M62h1bVOydwY8i4y(LocalizedString("Subscribing，wait..."))
        print("purchaseProductWithIdentifier>purchaseProduct: ",productIdentifier)
        VUJhPmLtu5fO4mno(product)
    }
    
    // 购买指定产品
    func VUJhPmLtu5fO4mno(_ product: SKProduct) {
        if SKPaymentQueue.canMakePayments() {
            let payment = SKPayment(product: product)
            SKPaymentQueue.default().add(payment) //此句后会弹出账号登录
        } else {
            self.l0JOXR3PG9RznwqZ()
            self.view.Qianli_Toast(LocalizedString("Device Not Support"))
        }
    }
    
    func Ep3SoScAZ7qRlxNy(_ msg:String){
        DispatchQueue.main.async {[weak self] in
            if let self=self,let sender = self.TSNV8TJjZSPRpwR7{
                sender.isEnabled = true
                sender.setTitle(LocalizedString("Pay Now"), for: .normal)
            }
            self?.l0JOXR3PG9RznwqZ()
            if !msg.isEmpty{
                self?.view.Qianli_Toast(msg)
            }
        }
    }
    
    // 恢复购买
    func eRHMP1CJUp9BCa5l() {
//用于让用户恢复之前购买过的非消耗型 (in-app) 产品或自动续期订阅
//以下场景中会被触发:用户更换设备\应用卸载后重新安装\订阅管理
//通常在应用中添加一个 **"恢复购买" 按钮 **，让用户主动点击触发 restorePurchases
        print("restorePurchases")
        SKPaymentQueue.default().restoreCompletedTransactions() //会触发paymentQueue回调.restored流程
        
    }
    
//    SKPaymentTransactionObserver
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        for transaction in transactions {
            // 打印状态和交易ID
            print("paymentQueue>Transaction ID: \(transaction.transactionIdentifier ?? "unknown"), State: \(transaction.transactionState)")
//eg: paymentQueue>Transaction ID: 2000000952258470, State: SKPaymentTransactionState(rawValue: 1)
            switch transaction.transactionState {
            case .purchased: //=1
                slSNSvgxh3orEtrm(transaction) //操作完成，成功购买会走到这里
            case .restored: //=3
                t5tYcJNlGoxcIgiv(transaction)
            case .failed: //=2
                obuzDyzAVvuz2Vjj(transaction)
            case .deferred: //= 4
                self.view.Qianli_Toast(LocalizedString("Transaction delayed processing"))
            case .purchasing: //=0
                break
            @unknown default:
                break
            }
        }
    }
    

    func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
//恢复购买完成时回调
        print("paymentQueueRestoreCompletedTransactionsFinished")
        
        if queue.transactions.isEmpty {
//            self.view.Qianli_Toast("没有可恢复的购买记录")
            self.Ep3SoScAZ7qRlxNy(LocalizedString("Restore is Null"))
        } else {
//            self.view.Qianli_Toast(LocalizedString("Purchase has been restored"))// "购买已恢复"
            self.Ep3SoScAZ7qRlxNy(LocalizedString("Purchase has been restored"))
        }
    }
        
    func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
        print("paymentQueue>err:",error.localizedDescription)
        vBKiXyof0wEAB3PZ(nil, error: error)
    }
    
    private func vBKiXyof0wEAB3PZ(_ transaction: SKPaymentTransaction?, error: Error? = nil) {
        // 处理购买失败逻辑
        if let error = error as NSError?, error.code != SKError.paymentCancelled.rawValue {
//            self.view.Qianli_Toast("\(LocalizedString("Subscribe Failed")): \(error.localizedDescription)")
            self.Ep3SoScAZ7qRlxNy("\(LocalizedString("Subscribe Failed")): \(error.localizedDescription)")
        } else {
//            self.view.Qianli_Toast(LocalizedString("Subscribe Canceled"))
            self.Ep3SoScAZ7qRlxNy(LocalizedString("Subscribe Canceled"))
        }
        
        if let transaction = transaction {
            SKPaymentQueue.default().finishTransaction(transaction)
        }
    }
    
    // 刷新商品缓存
    private func aNsv69HdWGYcOZTU(completion: @escaping () -> Void) {
        let productIDs = Set(_innerProducts.map { $0.productIdentifier })
        let request = SKProductsRequest(productIdentifiers: productIDs)
        request.delegate = self
        request.start()
        // 刷新完成后回调
        completion()
    }
    
    
    // 购买成功
    private func slSNSvgxh3orEtrm(_ transaction: SKPaymentTransaction) {
        // 验证交易凭证
        aTj0WblVxh0Q9h7V(transaction: transaction,isRestored: false)
    }
    
    // 恢复购买
    private func t5tYcJNlGoxcIgiv(_ transaction: SKPaymentTransaction) {
        // 验证交易凭证
        aTj0WblVxh0Q9h7V(transaction: transaction,isRestored: true)
    }
    
    // 购买失败
    private func obuzDyzAVvuz2Vjj(_ transaction: SKPaymentTransaction) {
        var errorMessage = LocalizedString("Subscribe Failed")
        if let error = transaction.error as NSError? {
            if error.code != SKError.paymentCancelled.rawValue {
                errorMessage = "\(LocalizedString("Subscribe Failed")): \(error.localizedDescription)"
            } else {
                errorMessage = LocalizedString("Subscribe Canceled")
            }
        }
        // 完成交易
        SKPaymentQueue.default().finishTransaction(transaction)
        self.Ep3SoScAZ7qRlxNy(errorMessage)
//        self.view.Qianli_Toast(errorMessage)
    }
    
    // 验证交易凭证
    private func aTj0WblVxh0Q9h7V(transaction: SKPaymentTransaction,isRestored:Bool) {
        SKPaymentQueue.default().finishTransaction(transaction)
        
        guard let receiptURL = Bundle.main.appStoreReceiptURL,
              let receiptData = try? Data(contentsOf: receiptURL) else { //10082byte的数据
            Ep3SoScAZ7qRlxNy(LocalizedString("Get Receipt Fail"))
//            self.view.Qianli_Toast(LocalizedString("Get Receipt Fail"))
            return
        }
        self.M62h1bVOydwY8i4y(LocalizedString("Completing subscription..."))
// receiptURL=file:///private/var/mobile/Containers/Data/Application/0F352CBF-B7A0-44D6-A4B3-54A83411929F/StoreKit/sandboxReceipt
//Bundle.main.appStoreReceiptURL 在沙盒环境下为上面的值,在生产环境会自动是另一个值
        
        // 将收据数据发送到您的服务器进行验证,或直接使用Apple的验证服务（生产环境建议使用我们自己的服务器验证，由服务器去请求苹果进行验证）
        let receiptString = receiptData.base64EncodedString(options: [])
        let stype = isRestored ? "恢复购买" : "购买商品"
        print("verifyReceipt>\(stype):\(transaction.transactionIdentifier ?? "unknown")") //:\n\(receiptString)
//eg: verifyReceipt>购买商品:2000000952258470
//将凭证数据发给服务，由服务端用此凭证去请求苹果进行验证
        
        B4nVOM4Q5Sbule8l(receiptString: receiptString, transaction: transaction,isRestord: isRestored)
        
    }
    
    // 发送收据到服务器
    private func B4nVOM4Q5Sbule8l(receiptString: String, transaction: SKPaymentTransaction,isRestord:Bool) {
        // 实际项目中，这里应该将receiptString发送到您的服务器
        // 服务器再将其发送到Apple的验证服务
        print("sendReceiptToServer>receiptString:\n",receiptString)
        //transaction.payment.productIdentifier 没啥用
//        let originalId =  transaction.original?.transactionIdentifier //上一次订阅订单ID（original可能为nil）
        if let transactionIdentifier = transaction.transactionIdentifier{  //主要是这个订单号，发给服务进行验证，
            print("sendReceiptToServer>transactionIdentifier: \(transactionIdentifier)")
        }
        VipViewModel.shared.EhAjgX7RNXBE6Vai(receiptStr: receiptString) { result in
            SKPaymentQueue.default().finishTransaction(transaction)
            DispatchQueue.main.async {[weak self] in
                switch result{
                case .success(let orderinfo):
                    if orderinfo.code == 0{
                        self?.rpuuoOnK5m7HAPCB(orderinfo.msg,isRestord)
                    }else{
                        self?.addSMcKgGcpLwTGr("[\(orderinfo.code)]\(orderinfo.msg)")
                    }
                case .failure(let err):
                    self?.addSMcKgGcpLwTGr(err.localizedDescription)
                }
            }
        }
    }
    
    private func rpuuoOnK5m7HAPCB(_ trade_status:String,_ isRestord:Bool = false){
        if trade_status == "TRADE_SUCCESS"{
//            self.view.Qianli_Toast(isRestord ? LocalizedString("Purchase has been restored") : LocalizedString("Purchase completed"))
            self.Ep3SoScAZ7qRlxNy(isRestord ? LocalizedString("Purchase has been restored") : LocalizedString("Purchase completed"))
        }else{
            self.Ep3SoScAZ7qRlxNy("result：\(trade_status)")
        }
    }
    
    private func addSMcKgGcpLwTGr(_ errMsg:String,_ isRestord:Bool = false){
        
        if(errMsg.isEmpty){
//            self.view.Qianli_Toast(isRestord ? LocalizedString("Purchase has been restored") : LocalizedString("Purchase completed"))
            self.Ep3SoScAZ7qRlxNy(isRestord ? LocalizedString("Purchase has been restored") : LocalizedString("Purchase completed"))
        }else{
//            self.view.Qianli_Toast(errMsg)
            self.Ep3SoScAZ7qRlxNy(errMsg)
        }
    }
    
    
    private func Da7EdB35F2bgWotg() -> String? {
        if let code = Locale.current.regionCode{
            print("getCurrentRegionCode>",code)
            return code
        }
        return ""
    }
    
    // 判断当前是否为中国大陆地区
    private func WEYB1XUAo2P2ZCtt() -> Bool {
        return Da7EdB35F2bgWotg() == "CN"
    }
}
